package com.maolong.controller.item;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maolong.entity.domain.Item;
import com.maolong.entity.format.Code;
import com.maolong.entity.format.RespResult;
import com.maolong.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    IItemService itemService;

    /**
     * 查询商品信息，可以接收商品名称，特定查询，若无，查全部
     * 完成了分页功能
     * @param name
     * @return
     */
    @GetMapping
    public RespResult productList(@RequestParam(value = "name",required = false)String name,
                                  @RequestParam(value = "currentPage",required = false)Long page,
                                  @RequestParam(value = "pageSize",required = false)Long size) {

        log.info("查询的商品名称是{},当前页码{},当前页数{}",name,page,size);
        if(page == null&&size == null&&name==null) {
            return new RespResult(Code.ITEM_SELECT_OK,itemService.count(),"查询成功");
        }
        Page<Item> pages = new Page<>(page, size);
        List<Item> list;
        if(name == null||"".equals(name)) {
            list = itemService.page(pages).getRecords();
        }else{
            QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name",name);
            list=itemService.page(pages,queryWrapper).getRecords();
        }
        log.info("查询到的数据是{}",list);
        System.out.println(list);
        return new RespResult(Code.ITEM_SELECT_OK,list,"查询成功");
    }

    /**
     * 删除指定id
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public RespResult deleteItem(@PathVariable(required = false,value = "id") Long id) {
        log.info("删除的序号是{}",id);
        boolean b = itemService.removeById(id);
        log.info("删除的结果是{}",b);
        return new RespResult(b==true?Code.ITEM_DELETE_OK:Code.ITEM_DELETE_FAIL,null,"删除成功");
    }

    /**
     * 插入商品
     * @param item
     * @return
     */
    @PostMapping
    public RespResult addItem(@RequestBody Item item) {
        log.info("添加的物品{}",item);
        boolean b = itemService.save(item);
        log.info("添加的结果是{}",b);
        return new RespResult(b==true?Code.ITEM_ADD_OK:Code.ITEM_ADD_FAIL,null,"添加成功");
    }

    /**
     * 修改商品信息
     * @param item
     * @return
     */
    @PutMapping
    public RespResult updateItem(@RequestBody Item item) {
        log.info("修改的参数是{}",item);
        boolean b = itemService.updateById(item);
        log.info("修改的结果是{}",b);
        return new RespResult(b==true?Code.ITEM_UPDATE_OK:Code.ITEM_UPDATE_FAIL,null,"修改成功");
    }
}
